<?php
require_once(dirname(__FILE__).'/Abstract.php');
class TranslateMetier extends AbstractSystemMetier 
{
    protected static $_LANG = null;
    
    public static function loadLang($iso_code = null) {
		global $_LANG;
        
        if (self::$_LANG == null) {
            if (empty($iso_code)) $iso_code = NZ_Config::$defaultLang;
            require_once ((BASEPATH == '/')?'':dirname(BASEPATH)).'/'.APPPATH.'language/'.$iso_code.'.php';
            self::$_LANG = $_LANG;
        }
    }
    
	/**
	 * Get a translation for an admin controller
	 *
	 * @param $string
	 * @param string $class
	 * @param bool $addslashes
	 * @param bool $htmlentities
	 * @return string
	 */
	public static function getTranslation($string, $class = 'Translate', $iso_code = null, $addslashes = false, $htmlentities = true)
	{
		self::loadLang($iso_code);

		$key = md5(str_replace('\'', '\\\'', $string));
		if (isset(self::$_LANG[$class.$key]))
			$str = self::$_LANG[$class.$key];
		else
			$str = self::getGenericTranslation($string, $key, self::$_LANG);
        
		if ($htmlentities)
			$str = htmlentities($str, ENT_QUOTES, 'utf-8');
		$str = str_replace('"', '&quot;', $str);

		return ($addslashes ? addslashes($str) : stripslashes($str));
	}

	/**
	 * Return the translation for a string if it exists for the base AdminController or for helpers
	 *
	 * @static
	 * @param $string string to translate
	 * @param null $key md5 key if already calculated (optional)
	 * @param $lang_array global array of admin translations
	 * @return string translation
	 */
	public static function getGenericTranslation($string, $key = null, &$lang_array)
	{
		if (is_null($key))
			$key = md5(str_replace('\'', '\\\'', $string));

		if (isset($lang_array['Translate'.$key]))
			$str = $lang_array['Translate'.$key];
		else
			$str = $string;

		return $str;
	}

	/**
	 * Check if string use a specif syntax for sprintf and replace arguments if use it
	 *
	 * @param $string
	 * @param $args
	 * @return string
	 */
	public static function checkAndReplaceArgs($string, $args)
	{
		if (preg_match_all('#(?:%%|%(?:[0-9]+\$)?[+-]?(?:[ 0]|\'.)?-?[0-9]*(?:\.[0-9]+)?[bcdeufFosxX])#', $string, $matches) && !is_null($args))
		{
			if (!is_array($args))
				$args = array($args);

			return vsprintf($string, $args);
		}
		return $string;
	}
}